let socket;
function connectWebSocket() {
    socket = new WebSocket(getWebSocketUrl("/api/ws/gbi"));

    socket.onopen = function() {
        console.log('WebSocket connection opened');
    };

    socket.onmessage = function(event) {
        const data = event.data;
        try {
            const response = JSON.parse(data);
            console.log('Received DataAnalysisResponse:', response);

            // 处理 response 对象
            const { sessionId, requestId, evidence, eventName, rewrite, sql, resData, sqlError, visualization, visualizationData} = response;
            const visualizationDataJson = visualizationData ? JSON.stringify(visualizationData) : "";

            document.getElementById('sessionId').value = sessionId;
            // 示例：将数据追加到输出区域
            document.getElementById('output').innerHTML = `sessionId: ${sessionId}<br/>`;
            document.getElementById('output').innerHTML += `requestId: ${requestId}<br/>`;
            document.getElementById('output').innerHTML += `Event Name: ${eventName}<br/>`;
            document.getElementById('output').innerHTML += `Rewrite: ${rewrite}<br/>`;
            document.getElementById('output').innerHTML += `evidence: ${evidence}<br/>`;
            document.getElementById('output').innerHTML += `SQL: ${sql}`;
            document.getElementById('output').innerHTML += `<br/> ${sqlError}`;
            document.getElementById('output2').innerHTML = `${visualization}`;
            document.getElementById('output3').innerHTML = `${visualizationDataJson}`;
            
            
            // 显示表格
            if (resData) {
                var $p = $("#outputTable");
                resetPreviewTabs($p);
                var view_id = setPreviewTabs($p);
                //格式化json
                var $jsonView = $p.find('.json_view');
                var rowsLength = resData.length;
                if (resData && resData.length <= 500) {
                    // 如果返回值在500行以内，将json格式化显示
                    $jsonView.JSONView(data);
                } else if (resData && resData.length >= 1000) {
                    // 如果返回值在1000行以上，不格式化返回值, 并仅保留最多1000行
                    resData.splice(1000, resData.length-2);
                    var jsonData = JSON.stringify(resData);
                    $jsonView.text(jsonData);
                    $jsonView.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，已禁用json格式化, 并仅保留最多1000行。</div>");
                } else {
                    // 如果返回值在500行以上，不格式化返回值，因为格式化太大json会卡死浏览器
                    var jsonData = JSON.stringify(resData);
                    $jsonView.text(jsonData);
                    $jsonView.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，已禁用json格式化。</div>");
                }
    
                // 显示表格
                // class=fixed
                $jsonView.after("<div id='view_table_"+view_id+"' class='iframe_preview tab-pane'><table class='table table-condensed tableTarget table-striped table-bordered table-hover margin0 tablesorter tablesorter-default'><thead><tr class='info'><th>-</th></tr></thead><tbody class='trTarget max-height200'><tr><td class='prompt'>暂无数据</td></tr></tbody></table></div>");
                var $iframe_preview = $jsonView.parent().find(".iframe_preview");
//                showDatasByData(data, $iframe_preview, endTime-startTime);
                showDatasByDataGbi(resData, $iframe_preview);

                // 图表
    //            showCharParam(data, $p2, view_id, $jsonView, $view_param);
            }
        } catch (error) {
            document.getElementById('output').innerHTML += `计算失败: ${sqlError}`;
        }
    };

    socket.onclose = function() {
        console.log('WebSocket connection closed');
    };

    socket.onerror = function(error) {
        console.error('WebSocket error:', error);
    };
}

function sendRequest() {
    const input = document.getElementById('gbi_input').value;
    const requestData = {
        query: input,
        sessionId: document.getElementById('sessionId').value,
        tenantId: document.getElementById('tenantId').value,
        cinemaUid: document.getElementById('cinemaUid').value
    };
    const message = JSON.stringify(requestData);
    document.getElementById('output').innerHTML = "思考中...";
    document.getElementById('output2').innerHTML = "思考中...";
    document.getElementById('output3').innerHTML = "思考中...";
    
    resetPreviewTabs($("#outputTable"));
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(message);
    } else {
        connectWebSocket();
        socket.onopen = function() {socket.send(message);};
        console.log('WebSocket is not connected. Attempting to connect...');
    }
}

function getWebSocketUrl(subUrl) {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const host = window.location.host;
    const pathname = window.location.pathname;
    
    // 提取第一级目录
    const pathParts = pathname.split('/').filter(part => part.length > 0);
    const firstLevelDirectory = pathParts.length > 0 ? pathParts[0] : '';
    
    return `${protocol}//${host}/${firstLevelDirectory}/${subUrl}`;
}


var showDatasByDataGbi = function(resData, $div, currentSecMills) {
    $view_div = $div.closest('.view_div');
    $view_div.find('.tab_rows').text('');
    if (resData && resData.length > 0) {
        loadDataToTable(resData, $div, "#defaultsTemplate");
        $div.find(".tablesorter").tablesorter();
        $view_div.find('.tab_view_table').click();
        var text = "返回["+resData.length+"]条结果 ";
        if (currentSecMills) {
            var currentSec = currentSecMills / 1000;
            text += (currentSec > 100 ? currentSec.toFixed(0) + "秒 " : currentSec.toFixed(2) + "秒 ");
        }

        $view_div.find('.tab_rows').text(text);
        if (resData.length <= 1000) {
            // 导出数据  为 csv 文件
            var csvDownload = $("<a href='###' title='直接导出以下表格的数据到csv文件' >导出表格</a>")
            csvDownload.on("click", function(){downloadJson2Csv(resData)});
            var csvDownloadLi = $("<li class='tab_clear' style='float:right'></li>")
            csvDownloadLi.append(csvDownload);
            $view_div.find('.tab_rows').closest('li').before(csvDownloadLi);
            
            // 复制到粘贴板
            var tsvDownload = $("<a href='###' title='复制以下表格的数据到粘贴板' >复制到粘贴板</a>")
            tsvDownload.on("click", function(){downloadJson2Tsv(resData)});
            var tsvDownloadLi = $("<li class='tab_clear' style='float:right'></li>")
            tsvDownloadLi.append(tsvDownload);
            $view_div.find('.tab_rows').closest('li').before(tsvDownloadLi);
        }

        var tableFixed = $("<a href='###' title='对齐列宽' >对齐列宽</a>")
        tableFixed.on("click", function(){
            $table = $view_div.find('table');
            if ($table.hasClass("tableFixed")) {
                $table.removeClass("tableFixed");
                $(this).removeClass("active");
            } else {
                $table.addClass("tableFixed");
                $(this).addClass("active");
            }
        });
        var tableFixedLi = $("<li class='tab_tableFixed' style='float:right'></li>")
        tableFixedLi.append(tableFixed);

        if (resData.length > 1000) {
            $dev.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，只显示前1000条数据，如需导出大量数据，建议直接导出csv。</div>");
        }
        $view_div.find('.tab_rows').closest('li').before(tableFixedLi);

    } else {
        $div.find('.prompt').text('没有查询到数据!');
    }
}